<template>
  <el-form ref="form" :model="formData" label-width="80px">
    <el-form-item label="菜单名称">
      <el-input v-model="formData.name"></el-input>
    </el-form-item>

    <el-form-item label="菜单路径">
      <el-input v-model="formData.href"></el-input>
    </el-form-item>

    <el-form-item label="上级菜单">
      <el-select v-model="formData.parentId" placeholder="请选择上级菜单">
        <el-option label="顶级菜单" :value="-1"></el-option>
        <el-option
          v-for="menu in topMenus"
          :key="menu.id"
          :label="menu.name"
          :value="menu.id"
        ></el-option>
      </el-select>
    </el-form-item>

    <el-form-item label="描述">
      <el-input v-model="formData.description"></el-input>
    </el-form-item>

    <el-form-item label="图标名称">
      <el-input v-model="formData.icon"></el-input>
    </el-form-item>

    <el-form-item label="是否显示">
      <el-radio-group v-model="formData.shown">
        <el-radio :label="true">是</el-radio>
        <el-radio :label="false">否</el-radio>
      </el-radio-group>
    </el-form-item>

    <el-form-item label="排序">
      <el-input v-model="formData.orderNum"></el-input>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="onSubmit">立即{{ msg }}</el-button>
      <el-button>取消</el-button>
    </el-form-item>
  </el-form>
</template>
<script>
import { createOrUpdateMenu, getEditMenuInfo } from '@/api/menu'

export default {
  name: 'MenuCreateOrEdit',
  data () {
    return {
      isCreate: true,
      formData: {
        id: undefined,
        parentId: -1,
        name: '',
        href: '',
        icon: '',
        orderNum: 0,
        description: '',
        shown: true
      },
      topMenus: []
    }
  },
  created () {
    this.isCreate = !this.$route.params.id
    // 获取菜单详情 顶级菜单信息
    this.loadEditMenuInfo()
  },
  computed: {
    msg () {
      return this.isCreate ? '添加' : '更新'
    }
  },
  methods: {
    onSubmit () {
      createOrUpdateMenu(this.formData).then((res) => {
        if (res.data.data) {
          this.$message.success(`${this.msg}菜单成功`)
          this.$router.push({ name: 'menus' })
        } else {
          this.$message.success(`${this.msg}菜单失败`)
        }
      })
    },
    loadEditMenuInfo () {
      const { id = -1 } = this.$route.params
      getEditMenuInfo(id).then((res) => {
        if (res.data.code === '000000') {
          const { menuInfo, parentMenuList } = res.data.data
          this.topMenus = parentMenuList
          Object.assign(this.formData, menuInfo)
        } else {
          this.$message.error('获取菜单详情失败')
        }
      })
    }
  }
}
</script>
<style scoped lang='scss'>
.el-form {
  padding: 70px;
  background: #fff;
}
</style>
